package com.example.yan_music.presenter;

import android.content.SharedPreferences;
import android.os.SystemClock;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.util.Log;

import com.example.yan_music.app.XApplication;
import com.example.yan_music.base.presenter.BasePresenter;
import com.example.yan_music.bean.UserInfo;
import com.example.yan_music.bean.wangyi.Lyric;
import com.example.yan_music.bean.wangyi.NewSearchSong;
import com.example.yan_music.bean.wangyi.NewSongUrl;
import com.example.yan_music.bean.wangyi.SongAlbum;
import com.example.yan_music.contract.ISearchContract;
import com.example.yan_music.db.table.HistoryPlaySong;
import com.example.yan_music.event.PlayDurationEvent;
import com.example.yan_music.utils.SharePreferenceUtil;
import com.example.yan_music.utils.XDataPool;
import com.example.yan_music.utils.XLog;
import com.example.yan_music.utils.XToast;
import com.example.yan_music.widge.dialog.XDialog;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.nio.file.ClosedDirectoryStreamException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ISearchPresenterImp extends BasePresenter<ISearchContract.View> implements ISearchContract.Presenter {

    private static final String TAG = "ISearchPresenterImp";

    /**
     *  搜索
     * @param keywords 关键词
     * @param offset  页数
     * @return
     */
    @Override
    public void search(String keywords, int offset) {
        if(!keywords.equals("")){
            // 关键词不为空执行，返回搜索结果
            mModel.search(keywords,offset)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<NewSearchSong>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                            Log.d(TAG, "onSubscribe: ");
                            // 显示加载框
                            mView.showLoadingDialog();
                        }

                        @Override
                        public void onNext(NewSearchSong searchSong) {
                            if(searchSong.getCode() == 200){
                                // 进行网路请求，搜索歌曲并返回结果列表
                                mView.setSearchList((ArrayList<NewSearchSong.ResultBean.SongsBean>) searchSong.getResult().getSongs());
                            }else {
                                // TODO 没找到歌曲显示“无搜索结果”的页面
                            }
                        }

                        @Override
                        public void onError(Throwable e) {
                            // 网络错误弹出“网路错误”对话框
                            mView.showNetErrDialog();
                            mView.dismissLoadingDialog();
                            e.printStackTrace();
                        }

                        @Override
                        public void onComplete() {
                            Log.d(TAG, "onComplete: ");
                            // 隐藏加载框
                            mView.dismissLoadingDialog();
                            // 显示搜到多少首
                            mView.showSearchCount();
                            // 隐藏历史记录
                            mView.hideHistoryRecord();
                        }
                    });

        }else {
            //  关键词为空弹出对话框提示"再输入一次"
            mView.showKeywordsIsNullDialog();
        }
    }

    /**
     * 搜索更多
     *
     * @param keywords  关键词
     * @param offset    页数
     */
    @Override
    public void searchMore(String keywords, int offset) {
        if(!keywords.equals("")){
            mModel.search(keywords, offset)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<NewSearchSong>() {
                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(NewSearchSong searchSong) {
                            ArrayList<NewSearchSong.ResultBean.SongsBean> searchSongList =
                                    (ArrayList<NewSearchSong.ResultBean.SongsBean>) searchSong.getResult().getSongs();
                            if(searchSongList.size() == 0){
                                mView.showNoMoreDataDialog();
                            }else {
                                mView.searchMoreSuccess(searchSongList);
                            }
                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {
                            mView.finishLoadMore();
                        }
                    });
        }else {
            mView.showKeywordsIsNullDialog();
            mView.finishLoadMore();
        }
    }

    @Override
    public void getSongPlayUrl(final int songId, final String songName) {
        String cookie = (String)SharePreferenceUtil.get(XApplication.getContext(), "cookie", "无数据");
        Log.d(TAG, "getSongPlayUrl: " + cookie);
        mModel.getSongPlayUrl(songId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NewSongUrl>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NewSongUrl newSongUrl) {
                        if(newSongUrl.getCode() == 200){
                            // 播放地址
                            String playUrl = newSongUrl.getData().get(0).getUrl();
                            // 将该歌曲加入到播放历史表中
                            addToHistoryPlay(playUrl, songId, songName);
                            // 付费歌曲只有试听片段，这里需要拿到试听时长，然后设置给SeekBar最大值
                            if(newSongUrl.getData().get(0).getFreeTrialInfo() != null) {
                                XToast.showInfo("付费歌曲只能试听哦");
                                String realDurationStr = newSongUrl.getData().get(0).getFreeTrialInfo().toString().trim();
                                String startStr = realDurationStr.substring(7, realDurationStr.indexOf(","));
                                String endStr = realDurationStr.substring(realDurationStr.indexOf(",") + 6, realDurationStr.indexOf("}"));
                                float startTime = Float.parseFloat(startStr);
                                float endTime = Float.parseFloat(endStr);
                                // 试听歌曲的时长，单位ms
                                int duration = (int) (endTime - startTime) * 1000;
                                // 设置SeekBar的max
                                EventBus.getDefault().post(new PlayDurationEvent(duration, true));
                                Log.d(TAG, "onNext: 试听时长为：" + duration);
                            }
                            //XLog.d("onNext: " + "该歌曲播放地址为：" + playUrl);
                            mView.playSearchSong(playUrl);
                        }else {
                            // 提手用户播放失败
                            XToast.showError("骚瑞，好像没找到播放地址");
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void addToHistoryPlay(String playUrl, int songId, String songName) {

        if(LitePal.where("historyPlaySongId = ?", Integer.toString(songId)).find(HistoryPlaySong.class).isEmpty()){
            // 获取播放时的系统时间
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
            Date date = new Date(System.currentTimeMillis());
            String playTime = simpleDateFormat.format(date);
            // 设置数据并保存
            HistoryPlaySong hpSoong = new HistoryPlaySong();
            hpSoong.setHistoryPlaySongId(songId);
            hpSoong.setHistoryPlaySongName(songName);
            hpSoong.setHistoryPlaySongUrl(playUrl);
            hpSoong.setPlayTime(playTime);
            hpSoong.save();
        }
    }

    /**
     * 获取歌词
     * @param songId
     */
    @Override
    public void getSongLyric(final int songId) {
        mModel.getSongLyric(songId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Lyric>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Lyric lyric) {
                        String songLyric;
                        // 拿到歌词，(坑)测试得出有的歌曲没有歌词需要判断一下
                        if(lyric.getCode() == 200 && lyric.getLrc() != null){
                                songLyric = lyric.getLrc().getLyric();
                                mView.getSongLyric(songLyric);
                        }else {
                            songLyric = "暂无歌词";
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        Log.d(TAG, "onComplete: 歌词搜索完成");
                    }
                });
    }

    /**
     * 获取歌曲封面
     * 获取歌曲专辑
     * @param songId
     */
    @Override
    public void getSongAlbum(int songId) {
        mModel.getSongAlbum(songId)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<SongAlbum>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(SongAlbum songAlbum) {
                        String coverUrl;
                        if(songAlbum.getCode() == 200){
                             coverUrl = songAlbum.getAlbum().getPicUrl();
                             mView.getSongCoverUrl(coverUrl);
                        }else {
                            // 请求出错的时候设置上默认的图片url
                            coverUrl =  "https://p1.music.126.net/6y-UleORITEDbvrOLV0Q8A==/5639395138885805.jpg";
                        }
                        //XLog.d("该歌曲的封面图url为：" + coverUrl);
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onComplete() {
                        Log.d(TAG, "onComplete: 专辑搜索完成");
                    }
                });
    }

    @Override
    public void login(String phoneNum, String password) {
        mModel.login(phoneNum, password)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<UserInfo>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(UserInfo userInfo) {
                        String userName = userInfo.getProfile().getNickname();
                        String cookie = userInfo.getCookie();
                        SharePreferenceUtil.put(XApplication.getContext(), "cookie", cookie);
                        Log.d(TAG, "onNext: " + userName);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }
}
